﻿Imports System.Security.Cryptography

Public Class SimpleAes
    Implements IDisposable
    Private Aes As New AesCryptoServiceProvider

    Private Shared Function TruncateHash(ByVal key As String, ByVal length As Int32) As Byte()
        Dim sha1 As New SHA1CryptoServiceProvider

        ' Hash the key.
        Dim keyBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(key)
        Dim hash() As Byte = sha1.ComputeHash(keyBytes)

        ' Truncate or pad the hash.
        ReDim Preserve hash(length - 1)
        sha1.Dispose()
        Return hash
    End Function

    Sub New(ByVal key As String)
        ' Initialize the crypto provider.
        Aes.Key = TruncateHash(key, Aes.KeySize \ 8)
        Aes.IV = TruncateHash("", Aes.BlockSize \ 8)
    End Sub

    Public Function EncryptData(ByVal ptBytes As Byte()) As Byte()
        ' Create the stream.
        Dim ms As New System.IO.MemoryStream
        ' Create the encoder to write to the stream.
        Dim encStream As New CryptoStream(ms, Aes.CreateEncryptor(), CryptoStreamMode.Write)

        ' Use the crypto stream to write the byte array to the stream.
        encStream.Write(ptBytes, 0, ptBytes.Length)
        encStream.FlushFinalBlock()

        ' Convert the encrypted stream to a printable string.
        Return ms.ToArray()
    End Function

    Public Function DecryptData(cipherBytes As Byte()) As Byte()
        ' Create the stream.
        Dim ms As New System.IO.MemoryStream
        ' Create the decoder to write to the stream.
        Dim decStream As New CryptoStream(ms, Aes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
        ' Use the crypto stream to write the byte array to the stream.
        decStream.Write(cipherBytes, 0, cipherBytes.Length)
        decStream.FlushFinalBlock()

        ' Convert the plaintext stream to a string.
        Return ms.ToArray()
    End Function
    Private disposedValue As Boolean ' To detect redundant calls
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                'dispose managed state (managed objects).
                Aes.Dispose()
            End If
            'free unmanaged resources (unmanaged objects) and override Finalize() below.
            'set large fields to null.
        End If
        Me.disposedValue = True
    End Sub
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

End Class